package com.cskaoyan;

import com.cskaoyan.bean.Teacher;
import com.cskaoyan.utils.MybatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;

/**
 * 创建日期: 2022/08/01 14:35
 *
 * @author ciggar
 */
public class MybatisMain {

    public static void main1(String[] args) throws IOException {

        // 获取一个Mybatis的核心Bean， SqlSeesionFactory


       // 1. 读取核心配置文件
        InputStream stream = MybatisMain.class.getClassLoader().getResourceAsStream("mybatis-config.xml");

        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");


        // 2. 获取一个SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();


        // 3. 获取SqlSessionFactory
        SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(in);


        // 4. 获取SqlSession, 这个SQLSession实际上就是和数据库之间的一个连接（一个会话）
        SqlSession sqlSession = sessionFactory.openSession(true);
        // Connection connection = sqlSession.getConnection();
        // sqlSession.rollback();
        // sqlSession.commit();


        // 5. 执行SQL语句
        Teacher teacher = new Teacher();
        teacher.setId(2002);
        teacher.setName("山本");
        teacher.setNickname("特种兵");
        teacher.setGender("male");


        int affectedRows = sqlSession.insert("cskaoyan.insertTeacher", teacher);

        System.out.println("affectedRows:" + affectedRows);
    }

    // 删除
    public static void main2(String[] args) {

        SqlSession sqlSession = MybatisUtils.getSqlSession(true);

        int affectedRows = sqlSession.delete("cskaoyan.deleteTeacherById", 2002);

        System.out.println("affectedRows:" + affectedRows);


    }

    // 修改
    public static void main3(String[] args) {

        SqlSession sqlSession = MybatisUtils.getSqlSession(true);

        Teacher teacher = new Teacher();
        teacher.setName("马邦德");
        teacher.setId(2001);
        int affectedRows = sqlSession.update("cskaoyan.updateNameById", teacher);

        System.out.println("affectedRows:" + affectedRows);
    }


    // 查询
    public static void main(String[] args) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);

        Teacher teacher = sqlSession.selectOne("cskaoyan.selectTeacherById", 2001);

        System.out.println(teacher);


    }



}
